<?php

namespace app\uapi\controller;

use app\admin\model\GoodCategory;
use app\admin\model\KnscyGoodRelateTicket;
use app\admin\model\KnscyGoods;
use app\admin\model\KnscyTickets;
use app\common\controller\ApiController;
use app\common\service\GoodService;
use app\common\service\OrderService;
use app\common\service\TicketPriceService;
use app\common\service\WeginService;
use think\facade\Db;

class Goods extends ApiController
{
    public function search()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        $type = $this->request->post('type',2);
        $keyword = $this->request->post('keyword','');
        //转换一下传递来的门票类型
        $ticket_types = [  3,2,1 ];
        $type =  $ticket_types[$type] ?? 3;
//        $good_ids = KnscyTickets::alias('t')->where('t.ticket_type', $type)
//            ->leftjoin( KnscyGoodRelateTicket::getTable() ." r", 'r.ticket_id = t.id')
//            ->where('t.uniacid', WeginService::getUniacid())->column('r.good_id');

        $list = KnscyGoods::withoutGlobalScope(['uniacid'])-> alias('g')
            ->where('g.status', 1)
           // ->where('g.id','in', $good_ids)
            ->leftjoin(KnscyGoodRelateTicket::getTable() ." r", 'g.id = r.good_id')
            ->leftjoin(KnscyTickets::getTable() ." t", 't.id = r.ticket_id ')
            ->where('t.uniacid', WeginService::getUniacid())
            ->where('g.uniacid', WeginService::getUniacid())
            ->where('t.ticket_type', $type)
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('g.title', 'like', '%'.$keyword.'%')
                    ->whereOr('g.sub_title', 'like', '%'.$keyword.'%');
            })
            ->group('g.id')
//            ->join( KnscyGoodRelateTicket::getTable() ." r", 'g.id = r.good_id')
//            ->where("r.ticket_id","IN", function($query)use($type){
//                $query->table(KnscyTickets::getTable())->field("id")
//                    ->where('ticket_type', $type)
//                    ->where('uniacid', WeginService::getUniacid());
//            })
            ->field("g.*")
            ->order(Db::raw('g.sort=0,g.sort asc,g.id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item, $key) {

                GoodService::format_goods($item);
            });

        $this->success('success', $list);
    }
    public function relateGood()
    {
        //
        $list = KnscyGoods::where('status', 1)
            ->where('relate_ticket_ids', '<>', '')
            ->order(Db::raw('rand()'))
            ->paginate(
                [
                    'list_rows' => 3,
                    'page' => 1,
                ]
            )->each(function ($item, $key) {

                GoodService::format_goods($item);
            });

        $this->success('success', $list);
    }

    /**
     * 首页推荐商品
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function suggest()
    {
        $limit = $this->request->post('limit', 20);
        $page = $this->request->post('page', 1);
        //
        $list = KnscyGoods::where('status', 1)
            ->where('relate_ticket_ids', '<>', '')
            ->order(Db::raw('virtual_sales=0,virtual_sales desc,id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item, $key) {

                GoodService::format_goods($item);
            });

        $this->success('success', $list);
    }

    /**
     * 门票详情数据
     * @return void
     */
    public function ticketDetail()
    {
        $ticket_id = $this->request->post('ticket_id');
        $ticket = KnscyTickets::where('id', $ticket_id)->where('status', 1)->find();

        if (empty($ticket)) {
            $this->error('参数错误');
        }

        //关联 的文案
        $ticket['remark_list'] = GoodService::ticketInfos($ticket['remark']);

        //预留折扣数据
        $ticket['discount'] = OrderService::get_discount( $this->user_id);
        //需要录入几个出行人
        $ticket['need_people'] = 1;
        $tag[] = $ticket['can_refund'] ==1 ? '可退':'不可退';

        $tag[] = $ticket['need_check']==1 ? '需要换票':'无需换票' ;
        $ticket['tag'] = $tag;


        $this->success('成功', $ticket);
    }

    /**
     * 获取门票的两个月期间每天的价格
     * @return void
     */
    public function ticketPrice()
    {
        $ticket_id = $this->request->post('ticket_id');
        $ticket = KnscyTickets::where('id', $ticket_id)->where('status', 1)->find();

        if (empty($ticket)) {
            $this->error('参数错误');
        }

        $day =  TicketPriceService::get_start_day();
        $month = 3; //只查询往后2个月 的价格
        $prices = TicketPriceService::getMonthPriceList($day, $ticket_id, $month, false);

        //获取一年后的当天
        $month_last_day = date('Y-m-d', strtotime("+{$month} months", strtotime($day)));
        $month_price = [];
        $next_day = $day;
        do {
            //没有动态价格采用门票的价格
            $month_price[$next_day] = $prices[$next_day] ?? number_format($ticket->price) ;
            $next_day = date('Y-m-d', strtotime('+1 day', strtotime($next_day)));

        } while (strtotime($next_day) <= strtotime($month_last_day));


        $this->success('success', $month_price);
    }

    /**
     * 商品的详情接口
     */
    public function details()
    {
        $id = $this->request->post('id');

        $details = KnscyGoods::where('id', $id)->where('status', 1)->find();

        if (!$details) {
            $this->error('数据不存在');
        }
        //处理价格和logo
        GoodService::format_goods($details);
        //查询相关的门票
        $details['tickets'] = [];
        $ticket_ids = explode(',', $details['relate_ticket_ids']);
        if (!empty($ticket_ids)) {
            $ticket_ids = array_filter(array_unique($ticket_ids));
            $details['tickets'] = KnscyTickets::whereIn('id', $ticket_ids)
                ->order(Db::raw('sort=0,sort asc,id desc'))
                ->select()->each(function ($item, $key) use ($details) {
                    //没有设置动态价格 用门票的price值
                    $item->price_now = $details['ticket_price'][$item['id']] ?? number_format($details['price'] ?? 0);
                    //关联 的文案
                    $item['remark_list'] = GoodService::ticketInfos($item['remark']);

                });

        }

        $images = explode('|', $details['images']);
        $slides = [];
        if ($images) {
            foreach ($images as $image) {
                $slides[] = [
                    'thumb' => get_full_url($image)
                ];
            }
        }
        $details['slides'] = $slides;

        $this->success('success', $details);
    }

    /**
     * 预定页面 按一级分类查询子分类和产品
     */
    public function goodsByCate()
    {
        $pid = $this->request->post('pid');
        $cate_ids = GoodCategory::where('pid', $pid)->column('id');
        $cate_ids[] = $pid;
        $cate_data = GoodCategory::whereIn('id', $cate_ids)->column('id,pid, title', 'id');
        $list = KnscyGoods::where('status', 1)
            ->where('relate_ticket_ids', '<>', '')
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->whereIn('category_id', $cate_ids)
            ->paginate(
                [
                    'list_rows' => 50,
                    'page' => 1,
                ]
            )->each(function ($item, $key) {
                GoodService::format_goods($item);

            });
        foreach ($list->toArray()['data'] as $k => $v) {
            $cate_data[$v['category_id']]['goods'][] = $v;
        }
        $arr = array_values($cate_data);
        $goods = array_column($arr, 'goods');
        if (empty($goods)) {
            $arr = [];
        }

        $this->success('success', $arr);
    }


    public function cate()
    {
        $goodCategory = new GoodCategory();
        $list = $goodCategory->getPidMenuList();
        $cate1 = [];
        $cate2 = [];
        foreach ($list as $k => $v) {
            if ($v['pid'] == 0 && $v['id']) {
                $cate1[] = [
                    'id' => $v['id'],
                    'title' => $v['txt_title'],
                ];
            }
            if ($v['pid'] != 0 && $v['id']) {
                $cate2[$v['pid']][] = [
                    'id' => $v['id'],
                    'title' => $v['txt_title'],
                ];
            }

        }

        $this->success('success', [
            'cate1' => $cate1,
            'cate2' => $cate2
        ]);
    }

}